<template>
  <div v-loading="resultObj.loading">
    <el-card shadow="never">
      <div>
        <el-form ref="orderFormRef" :inline="true" :model="queryOrderObj" size="large">
          <el-form-item label="用户ID" prop="user_id">
            <el-input v-model="queryOrderObj.user_id" placeholder="用户ID" clearable style="width: 180px" />
          </el-form-item>
          <el-form-item label="用户名称" prop="username">
            <el-input v-model="queryOrderObj.username" placeholder="用户名称" clearable style="width: 200px" />
          </el-form-item>
          <el-form-item label="订单号" prop="order_nu">
            <el-input v-model="queryOrderObj.order_nu" placeholder="订单号" clearable style="width: 240px" />
          </el-form-item>
          <el-form-item label="是否消费" prop="status">
            <el-select v-model="queryOrderObj.status" placeholder="是否消费" clearable style="width: 180px">
              <el-option label="未支付（待核对）" :value="0" />
              <el-option label="支付成功（已核对）" :value="1" />
              <el-option label="支付成功（手工充值）" :value="2" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onCurrentChange('order', 1)" class="primary-btn">查询</el-button>
            <el-button type="info" @click="onReset('order', 1)" class="info-btn">重置</el-button>
            <el-button type="info" @click="onExport('order')" class="info-btn">导出</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="mt-10">
        <el-table :data="resultObj.orderData" border stripe style="width: 100%" class="j-table mt-0">
          <el-table-column prop="created_at" label="创建时间" />
          <el-table-column prop="order_nu" label="订单号" />
          <el-table-column prop="user_id" label="用户ID" />
          <el-table-column prop="username" label="用户名称" />
          <el-table-column label="代理类型">
            <template #default="scope">
              <p>
                <span v-if="scope.row.proxy_type == 1">动态类型</span>
                <span v-else-if="scope.row.proxy_type == 2">静态类型</span>
              </p>
            </template>
          </el-table-column>
          <el-table-column prop="goods_info" label="套餐" />
          <el-table-column label="支付方式/金额">
            <template #default="scope">
              <p>
                <span>{{ scope.row.pay_way_str }}</span>
                <span>/</span>
                <span>${{ scope.row.amount }}</span>
              </p>
            </template>
          </el-table-column>
          <el-table-column prop="pay_status" label="支付状态" />
          <el-table-column prop="remark" label="备注" />
          <el-table-column prop="action" label="操作" width="120px">
            <template #default="scope">
              <el-button type="primary" text v-if="scope.row.is_verify == 0" @click="onCheck(scope.row)">核对</el-button>
              <el-button
                type="primary"
                text
                v-if="scope.row.proxy_type == 2"
                @click="onRecharge(scope.row, 'staticRenewRecharge', '静态类型续费')"
                style="margin-left: 0"
                >续费</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <div class="j-pagination">
          <el-pagination
            background
            layout="prev, pager, next"
            :current-page="resultObj.orderPage"
            :pageSize="resultObj.orderLimit"
            :total="resultObj.orderTotal"
            @current-change="
              (val) => {
                onCurrentChange('order', val);
              }
            "
          />
        </div>
      </div>
    </el-card>

    <!-- 充值 -->
    <Recharge ref="rechargeRef" @confirm="onConfirm" />

    <!-- 核对 -->
    <Check ref="checkRef" @confirm="onConfirm" />
  </div>
</template>

<script lang="ts" setup>
  import { computed, onMounted } from 'vue';
  import { useRoute, useRouter } from 'vue-router';
  import { useUserStore } from '@/store/modules/user';
  import { setLang } from '@/i18n';
  import { useI18n } from 'vue-i18n';
  import {
    manageOrderApi,
    manageUserApi,
    payConfigApi,
    savePayConfigApi,
    manageResetPassApi,
    manageOrderExportApi,
    manageUserExportApi,
    manageLogApi,
    manageLogExportApi,
    manageStatisticsApi,
    manageStatisticsExportApi,
  } from '@/api/index';
  import type { FormInstance, FormRules, UploadProps } from 'element-plus';
  import { Plus } from '@element-plus/icons-vue';
  import dayjs from 'dayjs';
  import Recharge from '../components/recharge.vue';
  import Check from '../components/check.vue';

  const { locale } = useI18n();

  const route = useRoute();
  const router = useRouter();
  const userStore = useUserStore();

  const getUserInfo = computed(() => {
    let userInfo = userStore.getUserInfo || {};
    return userInfo;
  });

  const emits = defineEmits<{
    (event: 'confirm'): void;
    (event: 'page-change'): void;
  }>();

  const currentTab = ref('1');

  const imageUrl = ref('');
  const payConfigFormRef = ref<FormInstance>();
  const rechargeRef = ref();
  const checkRef = ref();

  const userFormRef = ref<FormInstance>();
  const orderFormRef = ref<FormInstance>();
  const logFormRef = ref<FormInstance>();
  const statisticsFormRef = ref<FormInstance>();

  const queryUserObj = reactive({
    user_id: '',
    username: '',
    is_buy: '',
    order_nu: '',
    status: '',
    distributor: ''
  });

  const queryOrderObj = reactive({
    user_id: '',
    username: '',
    is_buy: '',
    order_nu: '',
    status: '',
  });

  const queryLogObj = reactive({
    user_id: '',
    username: '',
    create_day: '',
    event_type: '',
    is_pay: '',
  });

  const queryStatisticsObj = reactive({});

  const resultObj = reactive({
    orderData: [],
    orderLimit: 20,
    orderPage: 1,
    orderTotal: 0,
    userData: [],
    userLimit: 20,
    userPage: 1,
    userTotal: 0,
    logData: [],
    logLimit: 20,
    logPage: 1,
    logTotal: 0,
    statisticsData: [],
    statisticsLimit: 20,
    statisticsPage: 1,
    statisticsTotal: 0,
    loading: false,
    currentTab: '',
  });

  const payConfigObj = reactive({
    id: '',
    usdt_address: '',
    usdt_qrcode: '',
    exchange_rate: '',
    alipay_switch: false,
    alipay_qrcode: '',
    weixin_switch: false,
  });

  const rules = reactive<FormRules>({
    usdt_address: [{ required: true, message: '请输入收款地址', trigger: 'change' }],
    usdt_qrcode: [{ required: true, message: '请上传收款二维码', trigger: 'change' }],
    exchange_rate: [{ required: true, message: '请输入美元兑人民币汇率值', trigger: 'change' }],
    alipay_qrcode: [{ required: true, message: '请上传支付宝二维码', trigger: 'change' }],
  });

  const onReset = (type, val) => {
    if (type == 'user') {
      userFormRef.value?.resetFields();
      resultObj.userPage = val;
      getUser();
    } else if (type == 'order') {
      orderFormRef.value?.resetFields();
      resultObj.orderPage = val;
      getOrder();
    } else if (type == 'log') {
      logFormRef.value?.resetFields();
      resultObj.logPage = val;
      getLog();
    } else if (type == 'statistics') {
      statisticsFormRef.value?.resetFields();
      resultObj.statisticsPage = val;
      getStatistics();
    }
  };

  const onTabChange = (val) => {
    if (val == '1') {
      onCurrentChange('user', 1);
    } else if (val == '2') {
      onCurrentChange('order', 1);
    } else if (val == '3') {
      managePayConfig();
    } else if (val == '4') {
      onCurrentChange('log', 1);
    } else if (val == '5') {
      onCurrentChange('statistics', 1);
    }
  };

  const getUser = async () => {
    // if (resultObj.loading) return false;
    resultObj.loading = true;
    resultObj.userData = [];
    manageUserApi({
      ...queryUserObj,
      limit: resultObj.userLimit,
      page: resultObj.userPage,
    })
      .then((res) => {
        if (res.data) {
          resultObj.userData = res.data.list;
          resultObj.userTotal = res.data.count;
        }
        resultObj.loading = false;
      })
      .catch((err) => {
        console.log('err', err);
        resultObj.loading = false;
        ElMessage.error(err.message);
      });
  };

  const getOrder = async () => {
    // if (resultObj.loading) return false;
    resultObj.loading = true;
    resultObj.orderData = [];
    manageOrderApi({
      ...queryOrderObj,
      limit: resultObj.orderLimit,
      page: resultObj.orderPage,
    })
      .then((res) => {
        if (res.data) {
          resultObj.orderData = res.data.list;
          resultObj.orderTotal = res.data.count;
        }
        resultObj.loading = false;
      })
      .catch((err) => {
        console.log('err', err);
        resultObj.loading = false;
        ElMessage.error(err.message);
      });
  };

  const managePayConfig = async () => {
    // if (resultObj.loading) return false;
    resultObj.loading = true;
    resultObj.orderData = [];
    payConfigApi({})
      .then((res) => {
        if (res.data) {
          payConfigObj.id = res.data.id;
          payConfigObj.usdt_address = res.data.usdt_address;
          payConfigObj.usdt_qrcode = res.data.usdt_qrcode;
          payConfigObj.exchange_rate = res.data.exchange_rate;
          payConfigObj.alipay_switch = res.data.alipay_switch;
          payConfigObj.alipay_qrcode = res.data.alipay_qrcode;
          payConfigObj.weixin_switch = res.data.weixin_switch;
        }
        resultObj.loading = false;
      })
      .catch((err) => {
        console.log('err', err);
        resultObj.loading = false;
        ElMessage.error(err.message);
      });
  };

  const getLog = async () => {
    // if (resultObj.loading) return false;
    resultObj.loading = true;
    resultObj.logData = [];
    manageLogApi({
      ...queryLogObj,
      limit: resultObj.logLimit,
      page: resultObj.logPage,
    })
      .then((res) => {
        if (res.data) {
          resultObj.logData = res.data.list;
          resultObj.logTotal = res.data.count;
        }
        resultObj.loading = false;
      })
      .catch((err) => {
        console.log('err', err);
        resultObj.loading = false;
        ElMessage.error(err.message);
      });
  };

  const getStatistics = async () => {
    // if (resultObj.loading) return false;
    resultObj.loading = true;
    resultObj.statisticsData = [];
    manageStatisticsApi({
      ...queryStatisticsObj,
      limit: resultObj.statisticsLimit,
      page: resultObj.statisticsPage,
    })
      .then((res) => {
        if (res.data) {
          resultObj.statisticsData = res.data.list;
          resultObj.statisticsTotal = res.data.count;
        }
        resultObj.loading = false;
      })
      .catch((err) => {
        console.log('err', err);
        resultObj.loading = false;
        ElMessage.error(err.message);
      });
  };

  const onCurrentChange = (type, val) => {
    if (type == 'user') {
      resultObj.userPage = val;
      getUser();
    } else if (type == 'order') {
      resultObj.orderPage = val;
      getOrder();
    } else if (type == 'log') {
      resultObj.logPage = val;
      getLog();
    } else if (type == 'statistics') {
      resultObj.statisticsPage = val;
      getStatistics();
    }
  };

  const handleAvatarSuccess: UploadProps['onSuccess'] = (response, uploadFile) => {
    imageUrl.value = URL.createObjectURL(uploadFile.raw!);
  };

  const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/ipg' && rawFile.type !== 'image/png') {
      ElMessage.error('仅支持上传jpg/jpeg/png格式的图片！');
      return false;
    } else if (rawFile.size / 1024 / 1024 > 2) {
      ElMessage.error('仅支持上传2MB以内大小的图片！');
      return false;
    }
    return true;
  };

  const parseTime = (val: string) => {
    return val ? dayjs(val).format('YYYY-MM-DD HH:mm:ss') : '';
  };

  const onSavePayConfig = async (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    await formEl.validate((valid, fields) => {
      if (valid) {
        onSavePayConfigFn();
      }
    });
  };

  const onSavePayConfigFn = async () => {
    if (resultObj.loading) return false;
    resultObj.loading = true;
    savePayConfigApi(payConfigObj)
      .then((res) => {
        ElMessage.success(res.message || res.errmsg);
        resultObj.loading = false;
        // if (res.errcode == 0) {
        //   managePayConfig();
        // }
      })
      .catch((err) => {
        console.log('err', err);
        resultObj.loading = false;
        ElMessage.error(res.message || res.errmsg);
      });
  };

  const onRecharge = async (row, type, title) => {
    rechargeRef.value.onOpen(row, type, title);
  };

  const onResetPwd = (row) => {
    ElMessageBox.confirm('是否确定重置此用户登录密码为：IPXPROXYCOM？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
      .then(() => {
        onResetPwdFn(row);
      })
      .catch(() => {});
  };

  const onResetPwdFn = async (row) => {
    // if (resultObj.loading) return false;
    resultObj.loading = true;
    manageResetPassApi({ user_id: row.id })
      .then((res) => {
        ElMessage.success(res.message || res.errmsg);
        resultObj.loading = false;
      })
      .catch((err) => {
        console.log('err', err);
        resultObj.loading = false;
        ElMessage.error(err.message);
      });
  };

  const onCheck = async (row) => {
    checkRef.value.onOpen(row);
  };

  const onConfirm = async (type) => {
    if (type == 'recharge') {
      getUser();
    } else if (type == 'check') {
      getOrder();
    }
  };

  const onExport = (type) => {
    let params = null;
    let Fn = null;
    if (type == 'user') {
      params = {
        ...queryUserObj,
        limit: resultObj.userLimit,
        page: resultObj.userPage,
        is_export: 1,
      };
      Fn = manageUserExportApi;
    } else if (type == 'order') {
      params = {
        ...queryOrderObj,
        limit: resultObj.orderLimit,
        page: resultObj.orderPage,
        is_export: 1,
      };
      Fn = manageOrderExportApi;
    } else if (type == 'log') {
      params = {
        ...queryLogObj,
        limit: resultObj.logLimit,
        page: resultObj.logPage,
        is_export: 1,
      };
      Fn = manageLogExportApi;
    } else if (type == 'statistics') {
      params = {
        ...queryStatisticsObj,
        limit: resultObj.statisticsLimit,
        page: resultObj.statisticsPage,
        is_export: 1,
      };
      Fn = manageStatisticsExportApi;
    }

    if (Fn) {
      Fn(params);
    }
  };

  const toOrderTab = (row) => {
    queryOrderObj.user_id = row.id;
    queryOrderObj.username = row.username;
    currentTab.value = '2';
    onCurrentChange('order', 1);
  };

  const toLogTab = (row) => {
    queryLogObj.user_id = row.id;
    queryLogObj.username = row.username;
    currentTab.value = '4';
    onCurrentChange('log', 1);
  };

  onMounted(() => {
    queryOrderObj.user_id = route.query.id || '';
    queryOrderObj.username = route.query.username || '';
    resultObj.orderPage = 1;
    getOrder();
  });
</script>

<style scoped lang="scss">
  .avatar-uploader {
    height: 154px;
    width: 154px;
    border: 1px solid #dcdfe6;
    border-radius: 6px;
    cursor: pointer;
    overflow: hidden;

    &:hover {
      border-color: #157cfb;
      box-shadow: 0 0 0 1px #a0cbff inset;
    }
  }

  .avatar-uploader .avatar {
    height: 154px;
    width: 154px;
    display: block;
  }

  .avatar-uploader .el-upload {
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 154px;
    height: 154px;
    text-align: center;
  }
</style>
